package com.atguigu.gmall.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.bean.KeywordStats;
import com.atguigu.gmall.bean.ProductStats;
import com.atguigu.gmall.bean.ProvinceStats;
import com.atguigu.gmall.bean.VisitorStats;
import com.atguigu.gmall.service.KeywordStatsService;
import com.atguigu.gmall.service.ProductStatsService;
import com.atguigu.gmall.service.ProvinceStatsService;
import com.atguigu.gmall.service.VisitorStatsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/api/sugar")
public class SugarController {

    @Autowired
    ProductStatsService productStatsService;

    @Autowired
    ProvinceStatsService provinceStatsService;

    @Autowired
    VisitorStatsService visitorStatsService;

    @Autowired
    KeywordStatsService keywordStatsService;


    @RequestMapping("/gmv")
    public String getGMV(@RequestParam(value = "date",defaultValue = "0") Integer date){
        if(date == 0){
            date=now();
        }
        BigDecimal gmv = productStatsService.getGMV(date);
        System.out.println(date);
        System.out.println("gmv: "+ gmv);
        String json = "{\"status\":0,\"data\":" + gmv +"}";
        return  json;
    }


    @RequestMapping("/spu")
    public String getProductStatsGroupBySpu(
            @RequestParam(value = "date",defaultValue = "0") Integer date,
            @RequestParam(value = "limit",defaultValue = "10") int limit
    ){
        if(date ==0) {
            date = now();
        }
        //调用service层方法，获取按spu统计数据
        List<ProductStats> productStatsBySPUList = productStatsService.getProductStatsGroupBySpu(date, limit);
        //初始化表头信息
        StringBuilder jsonBuilder = new StringBuilder("{" +
                "\"status\": 0," +
                "\"data\": {" +
                "\"columns\": [{" +
                "\"name\": \"商品SPU名称\"," +
                "\"id\": \"spu_name\"" +
                "}," +
                "{" +
                "\"name\": \"交易额\"," +
                "\"id\": \"order_amount\"" +
                "}," +
                "{" +
                "\"name\": \"订单数\"," +
                "\"id\": \"order_ct\"" +
                "}" +
                "]," +
                "\"rows\": [");
        //对查询出来的数据进行遍历，将每一条遍历的结果封装为json的一行数据
        for (int i = 0; i < productStatsBySPUList.size(); i++) {
            ProductStats productStats = productStatsBySPUList.get(i);
            if (i >= 1) {
                jsonBuilder.append(",");
            }
            jsonBuilder.append("{" +
                    "\"spu_name\": \"" + productStats.getSpu_name() + "\"," +
                    "\"order_amount\":" + productStats.getOrder_amount() + "," +
                    "\"order_ct\":" + productStats.getOrder_ct() + "}"
            );
        }

        jsonBuilder.append("]}}");
        return jsonBuilder.toString();

    }


    // 品类接口
    @RequestMapping("/category3")
    public String getProductStatsGroupByCategory3(
            @RequestParam(value = "date",defaultValue = "0") Integer date,
            @RequestParam(value = "limit",defaultValue = "10") int limit
    ){
        if(date ==0) {
            date = now();
        }

        List<ProductStats> statsList = productStatsService.getProductStatsGroupByCategory3(date,limit);

        JSONObject jsonObject = new JSONObject();


        jsonObject.put("status",0);
        JSONArray data = new JSONArray();
        for(ProductStats productStats:statsList){
            data.add(getKV("name",productStats.getCategory3_name(),"value",productStats.getOrder_amount()));
        }
        jsonObject.put("data",data);
        return jsonObject.toJSONString();
    }



    //品牌接口
    @RequestMapping("/trademark")
    public String getProductStatsByTrademark(
            @RequestParam(value = "date",defaultValue = "0") Integer date,
            @RequestParam(value = "limit",defaultValue = "10") int limit
    ){
        if(date ==0) {
            date = now();
        }

        List<ProductStats> statsList = productStatsService.getProductStatsByTrademark(date,limit);


        List<String> tradeMarkList = new ArrayList<>();
        List<BigDecimal> amountList = new ArrayList<>();
        for(ProductStats productStats:statsList){
            tradeMarkList.add(productStats.getTm_name());
            amountList.add(productStats.getOrder_amount());
        }

        String json = "{\"status\":0,\"data\":{\"categories\":" +
                "[\"" + StringUtils.join(tradeMarkList,"\",\"") + "\"],\"series\":["
                +"{\"data\":["+ StringUtils.join(amountList,",") +"]}]}}";
        return json;
    }



    // 省级
    @RequestMapping("/province")
    public String getProvinceStats(@RequestParam(value = "date",defaultValue = "0") Integer date) {
        if(date ==0 ){
            date = now();
        }

        StringBuilder jsonBuilder = new StringBuilder("{\"status\":0,\"data\":{\"mapData\":[");
        List<ProvinceStats> provinceStatsList =  provinceStatsService.getProvinceStats(date);
        if(provinceStatsList.size()==0){

        }
        for(int i=0;i<provinceStatsList.size();i++){
            if (i>=1){
                jsonBuilder.append(",");
            }
            ProvinceStats provinceStats = provinceStatsList.get(i);
            jsonBuilder.append("{\"name\":\"" +provinceStats.getProvince_name() +"\",\"value\":" +
                    provinceStats.getOrder_amount() +" }");

        }
        jsonBuilder.append("]}}");
        System.out.println(jsonBuilder);
        return jsonBuilder.toString();
    }

    @RequestMapping("/visitor")
    public Map getVisitorStatsByNewFlag(@RequestParam(value = "date",defaultValue = "0") Integer date){
        if(date ==0) date= now();

        List<VisitorStats> visitorStatsByNewFlag = visitorStatsService.getVisitorStatsByNewFlag(date);
        VisitorStats newVisitorStats = new VisitorStats();
        VisitorStats oldVisitorStats = new VisitorStats();

        for(VisitorStats visitorStats: visitorStatsByNewFlag){
            System.out.println("visitorStats: "+visitorStats);
            if(visitorStats.getIs_new().equals("1")){
                newVisitorStats = visitorStats;
            }else{
                oldVisitorStats = visitorStats;
            }
        }


        //返回的json字符串的处理
        Map resMap = new HashMap();
        resMap.put("status", 0);
        Map dataMap = new HashMap();
        dataMap.put("combineNum", 1);

        //表头
        List columnList = new ArrayList();
        Map typeHeader = new HashMap();
        typeHeader.put("name", "类别");
        typeHeader.put("id", "type");
        columnList.add(typeHeader);

        Map newHeader = new HashMap();
        newHeader.put("name", "新用户");
        newHeader.put("id", "new");
        columnList.add(newHeader);

        Map oldHeader = new HashMap();
        oldHeader.put("name", "老用户");
        oldHeader.put("id", "old");
        columnList.add(oldHeader);
        dataMap.put("columns", columnList);

        //表格bady
        List rowList = new ArrayList();
        //用户数
        Map userCount = new HashMap();
        userCount.put("type", "用户数(人)");
        userCount.put("new", newVisitorStats.getUv_ct());
        userCount.put("old", oldVisitorStats.getUv_ct());
        rowList.add(userCount);

        //总访问页面
        Map pageTotal = new HashMap();
        pageTotal.put("type", "总访问页面(次)");
        pageTotal.put("new", newVisitorStats.getPv_ct());
        pageTotal.put("old", oldVisitorStats.getPv_ct());
        rowList.add(pageTotal);

        //跳出率
        Map jumRate = new HashMap();
        jumRate.put("type", "跳出率(%)");
        jumRate.put("new", newVisitorStats.getUjRate());
        jumRate.put("old", oldVisitorStats.getUjRate());
        rowList.add(jumRate);

        //平均在线时长
        Map ageDurTime = new HashMap();
        ageDurTime.put("type", "平均在线时长(秒)");
        ageDurTime.put("new", newVisitorStats.getDurPerSv());
        ageDurTime.put("old", oldVisitorStats.getDurPerSv());
        rowList.add(ageDurTime);

        //平均页面访问人数
        Map ageVisitCount = new HashMap();
        ageVisitCount.put("type", "平均访问人数(人次)");
        ageVisitCount.put("new", newVisitorStats.getPvPerSv());
        ageVisitCount.put("old", oldVisitorStats.getPvPerSv());
        rowList.add(ageVisitCount);

        dataMap.put("rows", rowList);
        resMap.put("data", dataMap);
        return resMap;

    }


    @RequestMapping("/hr")
    public String getVisitorStatsByHr(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        //从service层中获取分时访问数据
        List<VisitorStats> visitorStatsByHrList = visitorStatsService.getVisitorStatsByHour(date);

        //因为有的小时可能没有数据，为了把每个小时都展示出来，我们创建一个数组，用来保存每个小时对应的访问情况
        VisitorStats[] visitorStatsArr = new VisitorStats[24];
        for (VisitorStats visitorStats : visitorStatsByHrList) {
            visitorStatsArr[visitorStats.getHr()] = visitorStats;
        }

        //定义存放小时、uv、pv、新用户的List集合
        List<String> hrList = new ArrayList<>();
        List<Long> uvList = new ArrayList<>();
        List<Long> pvList = new ArrayList<>();
        List<Long> newVisitorList = new ArrayList<>();

        //对数组进行遍历，将0~23点的数据查询出来，分别放到对应的List集合中保存起来
        for (int i = 0; i <= 23; i++) {
            VisitorStats visitorStats = visitorStatsArr[i];
            if (visitorStats != null) {
                uvList.add(visitorStats.getUv_ct());
                pvList.add(visitorStats.getPv_ct());
                newVisitorList.add(visitorStats.getNew_uv());
            }else{
                uvList.add(0L);
                pvList.add(0L);
                newVisitorList.add(0L);
            }
            //小时位不足2位的时候，前面补0
            hrList.add(String.format("%02d",i));
        }
        //拼接字符串
        String json = "{\"status\":0,\"data\":{" + "\"categories\":" +
                "[\""+StringUtils.join(hrList,"\",\"")+ "\"],\"series\":[" +
                "{\"name\":\"uv\",\"data\":["+ StringUtils.join(uvList,",") +"]}," +
                "{\"name\":\"pv\",\"data\":["+ StringUtils.join(pvList,",") +"]}," +
                "{\"name\":\"新用户\",\"data\":["+ StringUtils.join(newVisitorList,",") +"]}]}}";
        return  json;

    }


    @RequestMapping("/keyword")
    public String getKeywordStats(@RequestParam(value = "date",defaultValue = "0") Integer date,
                                  @RequestParam(value = "limit",defaultValue = "20") Integer limit){
        if(date ==0) date =now();

        //查询数据
        List<KeywordStats> keywordStatsList = keywordStatsService.getKeywordStats(date,limit);

        StringBuilder jsonSb=new StringBuilder( "{\"status\":0,\"msg\":\"\",\"data\":[" );
        //循环拼接字符串
        for (int i = 0; i < keywordStatsList.size(); i++) {
            KeywordStats keywordStats =  keywordStatsList.get(i);
            if(i>=1){
                jsonSb.append(",");
            }
            jsonSb.append(  "{\"name\":\"" + keywordStats.getKeyword() + "\"," +
                    "\"value\":"+keywordStats.getCt()+"}");
        }
        jsonSb.append(  "]}");
        return  jsonSb.toString();
    }


    private int now(){
        String yyyyMMdd = DateFormatUtils.format(new Date(),"yyyyMMdd");
        return Integer.valueOf(yyyyMMdd);
    }


    public  JSONObject getKV(String key1,String value1,String key2,String value2){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key1,value1);
        jsonObject.put(key2,value2);
        return jsonObject;
    }

    public  JSONObject getKV(String key1,String value1,String key2,BigDecimal value2){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key1,value1);
        jsonObject.put(key2,value2);
        return jsonObject;
    }

    public  JSONObject getKV(String key1,String value1,String key2,BigDecimal value2,String key3,Long value3){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key1,value1);
        jsonObject.put(key2,value2);
        jsonObject.put(key3,value3);
        return jsonObject;
    }
}
